package org.jadelyre.utils;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public class ByteBufferUtils {
    public static final byte SPACE = 32;//空格
    public static final byte QUESTION_MARK = 63;//问号
    public static final byte FORWARD_SLASH = 47;//正斜杠
    public static final byte BACK_SLASH = 92;//\\
    public static final byte CR = 13;//\r
    public static final byte LF = 10;//\n
    public static final byte COL = 58;//:

    /**
     * 拼接两个bytebuffer，把可读部分的拼接成一个新的bytebuffer
     * @param previous
     * @param after
     * @return
     */
    public static ByteBuffer splice(ByteBuffer previous, ByteBuffer after) {
        int capacity = previous.remaining() + after.remaining();
        ByteBuffer spliceByteBuffer = ByteBuffer.allocate(capacity);
        spliceByteBuffer.put(previous);
        spliceByteBuffer.put(after);
        spliceByteBuffer.flip();
        return spliceByteBuffer;
    }

    /**
     * 复制
     * @param src
     * @return
     */
    public static ByteBuffer copy(ByteBuffer src){
        ByteBuffer newByteBuffer = ByteBuffer.allocate(src.remaining());
        newByteBuffer.put(src);
        newByteBuffer.flip();
        return newByteBuffer;
    }


    public static String readLine(ByteBuffer byteBuffer, String charset) {
        int startPosition = byteBuffer.position();
        int endPosition = 0;
        while (byteBuffer.hasRemaining()){
            if (byteBuffer.get() == CR){
                if (byteBuffer.get() == LF){
                    endPosition = byteBuffer.position() - 2;
                    break;
                }
            }
        }
        if (endPosition <= startPosition){
            return null;
        }
        int nowPosition = byteBuffer.position();
        byte[] bs = new byte[endPosition - startPosition];
        byteBuffer.position(startPosition);
        byteBuffer.get(bs);
        byteBuffer.position(nowPosition);
        try {
            return new String(bs, charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
